package test03;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 文件拷贝线程
 *
 * @author V
 * @date 2025-03-10
 */
public class CopyThread extends Thread {

    /**
     * 拷贝的源文件
     */
    private String source;

    /**
     * 拷贝的目标文件
     */
    private String target;

    /**
     * 拷贝文件的状态
     */
    private FileData fileData;


    public CopyThread() {

    }

    public CopyThread(String source, String target, FileData fileData) {
        this.source = source;
        this.target = target;
        this.fileData = fileData;
    }

    @Override
    public void run() {

        // 获取源文件对象
        File soruceFile = new File(source);

        // 获取目标文件对象
        File targetFile = new File(target);

        // 获取源文件对象的总容量
        long totalSize = soruceFile.length();
        this.fileData.setTotalSize(totalSize);

        // 实例化文件输入流、输出流，实现文件的读和写（拷贝）
        try (
                FileInputStream fis = new FileInputStream(soruceFile);
                FileOutputStream fos = new FileOutputStream(targetFile);
        ) {
            byte[] buffer = new byte[1024];
            int size ;
            while ((size = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, size);
                this.fileData.setCopiedSize(size);
                Thread.sleep(100);
            }
            System.out.println("完成进度：100 %");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}